import { useState, memo } from "react";
import { Button } from "antd";
import { createDownload, FILE_DOWNLOAD_URL } from "@/api/file";
import PropTypes from "prop-types";

const FileDownloadComponent = ({ title, path, ...resProps }) => {
  const [loading, setLoading] = useState(false);

  const onDownload = async () => {
    setLoading(true);
    const res = await createDownload(path);
    const fileName = path.split("/").pop();
    const root = document.body;
    const link = document.createElement("a");
    link.href = FILE_DOWNLOAD_URL + res;
    link.download = fileName;
    root.appendChild(link);
    link.click();
    root.removeChild(link);
  };

  return (
    <Button {...resProps} loading={loading} onClick={() => onDownload().finally(() => setLoading(false))}>
      {title}
    </Button>
  );
};
FileDownloadComponent.propTypes = {
  title: PropTypes.string,
  path: PropTypes.string,
};

export default memo(FileDownloadComponent);
